<template>
  <div>
    <div ref="vtkContainer" />
    <table v-if="activeObject" class="controls">
      <tbody>
        <tr>
          <td>
            <select
              style="width: 100%"
              :value="representation"
              @change="setRepresentation($event.target.value)"
            >
              <option value="0">Points</option>
              <option value="1">Wireframe</option>
              <option value="2">Surface</option>
            </select>
          </td>
        </tr>
        <tr>
          <td>
            <input
              type="range"
              min="1"
              max="30"
              :value="pointSize"
              @input="setPointSize($event.target.value)"
            />
          </td>
        </tr>
      </tbody>
    </table>
    <div v-if="loading" class="loading-indicator">Loading...</div>
    <div v-if="error" class="error-message">{{ error }}</div>
  </div>
</template>

<script setup>
import { ref, onMounted, onBeforeUnmount, watch } from 'vue';
import axios from 'axios';
import '@kitware/vtk.js/Rendering/Profiles/Geometry';
import vtkFullScreenRenderWindow from '@kitware/vtk.js/Rendering/Misc/FullScreenRenderWindow';
import vtkActor from '@kitware/vtk.js/Rendering/Core/Actor';
import vtkMapper from '@kitware/vtk.js/Rendering/Core/Mapper';
import vtkConeSource from '@kitware/vtk.js/Filters/Sources/ConeSource';
//import vtkGenericDataReader from '@kitware/vtk.js/IO/Core/GenericDataReader';
import vtkPolyDataReader from '@kitware/vtk.js/IO/Legacy/PolyDataReader';


// Define props
const props = defineProps({
  filename: String,
  serverUrl: {
    type: String,
    default: 'http://localhost:5000',
  },
});

// Reactive variables
const vtkContainer = ref(null);
const context = ref(null);
const representation = ref(2); // Surface representation by default
const pointSize = ref(2); // Default point size
const loading = ref(false);
const error = ref('');
const activeObject = ref(false);

// Methods
function setRepresentation(rep) {
  representation.value = Number(rep);
  updateActorProperties();
}

function setPointSize(size) {
  pointSize.value = Number(size);
  updateActorProperties();
}

function updateActorProperties() {
  if (context.value?.actor) {
    const { actor } = context.value;
    actor.getProperty().setRepresentation(representation.value);
    actor.getProperty().setPointSize(pointSize.value);
    context.value.renderWindow.render();
  }
}

// Load and render VTK file
const loadAndRenderVtkFile = async () => {
  if (!props.filename) {
    activeObject.value = false;
    return;
  }
  
  try {
    loading.value = true;
    error.value = '';
    activeObject.value = false;
    
    // Clear existing actor if exists
    if (context.value?.actor) {
      context.value.renderer.removeActor(context.value.actor);
      context.value.actor.delete();
      context.value.actor = null;
    }

    // Fetch VTK content from backend
    const response = await axios.get(
      `${props.serverUrl}/api/vtk-file/content/${props.filename}`,
      { responseType: 'text' }
    );

    // Initialize reader and parse VTK data
    // const reader = vtkGenericDataReader.newInstance();
    // reader.setInputDataString(response.data);
    // reader.update();
    // const data = reader.getOutputData(0);
    
    // if (!data) {
    //   throw new Error('Failed to parse VTK file');
    // }
    var cone = vtkConeSource.newInstance();

    // Create mapper and actor
    const mapper = vtkMapper.newInstance();
    //mapper.setInputData(data);
    mapper.setInputConnection(cone.getOutputPort());
    
    const actor = vtkActor.newInstance();
    actor.setMapper(mapper);
    
    // Apply initial properties
    //actor.getProperty().setRepresentation(representation.value);
    //actor.getProperty().setPointSize(pointSize.value);
    
    // Add to renderer and reset camera
    context.value.renderer.addActor(actor);
    context.value.renderer.resetCamera();
    context.value.renderWindow.render();
    
    // Update context
    context.value.actor = actor;
    context.value.mapper = mapper;
    //context.value.reader = reader;
    activeObject.value = true;
    
  } catch (err) {
    console.error('Error loading VTK file:', err);
    error.value = `Error: ${err.message}`;
  } finally {
    loading.value = false;
  }
};

// Initialize VTK environment
const initializeVtk = () => {
  if (vtkContainer.value && !context.value) {
    // Create full screen render window
    const fullScreenRenderer = vtkFullScreenRenderWindow.newInstance({
      rootContainer: vtkContainer.value,
    });
    
    // Get core VTK objects
    const renderer = fullScreenRenderer.getRenderer();
    const renderWindow = fullScreenRenderer.getRenderWindow();
    
    // Store in context
    context.value = {
      fullScreenRenderer,
      renderWindow,
      renderer,
      actor: null,
      mapper: null,
      reader: null
    };
  }
};

// Watch for filename changes
watch(() => props.filename, (newFilename) => {
  if (newFilename) {
    loadAndRenderVtkFile();
  }
});

// Lifecycle hooks
onMounted(() => {
  initializeVtk();
  if (props.filename) {
    loadAndRenderVtkFile();
  }
});

onBeforeUnmount(() => {
  if (context.value) {
    const { fullScreenRenderer, actor, mapper, reader } = context.value;
    
    // Clean up VTK objects
    if (actor) actor.delete();
    if (mapper) mapper.delete();
    if (reader) reader.delete();
    
    fullScreenRenderer.delete();
    context.value = null;
  }
});
</script>

<style scoped>
.controls {
  position: absolute;
  top: 25px;
  left: 25px;
  background: rgba(255, 255, 255, 0.7);
  padding: 12px;
  border-radius: 4px;
  z-index: 10;
}

.loading-indicator, .error-message {
  position: absolute;
  top: 25px;
  right: 25px;
  padding: 10px 15px;
  border-radius: 4px;
  font-weight: bold;
  z-index: 10;
}

.loading-indicator {
  background-color: #2196F3;
  color: white;
}

.error-message {
  background-color: #F44336;
  color: white;
}
</style>